<template>
    <el-form inline>
        <el-form-item label="标题：">
            <el-input v-model="queryTitle"></el-input>
        </el-form-item>
        <el-form-item style="float: right;">
            <el-button type="primary" @click="openSaveDialog(0)">
                <el-icon class="el-icon--left"><Plus /></el-icon>新增
            </el-button>
             <el-button type="primary" @click="importExcel()">
                <el-icon class="el-icon--left"><Upload /></el-icon>导入
            </el-button>
            <el-button type="primary" @click="exportExcel()">
                <el-icon class="el-icon--left"><Download /></el-icon>导出
            </el-button>
            <el-button type="primary" @click="exportStatistics()">
                <el-icon class="el-icon--left"><Download /></el-icon>统计
            </el-button>
            <el-button type="primary" @click="getData()">
                <el-icon class="el-icon--left"><Search /></el-icon>查询
            </el-button>
        </el-form-item>
    </el-form>

  <el-table v-loading="loading" :data="tableData" stripe border class="mytable">
    <el-table-column type="index" :index="getTableIndex" />
    <el-table-column prop="createTime" label="创建时间" />
    <el-table-column prop="updateTime" label="更新时间" />
    <el-table-column prop="createUser" label="创建人" />
    <el-table-column prop="updateUser" label="更新人" />
    <el-table-column prop="title" label="标题" />
    <el-table-column prop="content" label="内容" width="400" />
    <el-table-column prop="phone" label="电话" />
    <el-table-column>
        <template #default="scope">
            <el-button type="info" size="small" @click="openSaveDialog(scope.row)">修改</el-button>
            <el-button type="danger" size="small" @click="delData(scope.row)">删除</el-button>
        </template>
    </el-table-column>
  </el-table>

  <el-pagination background layout="prev, pager, next, total" 
                    :total="totalData" 
                    v-model:page-size="pageSize" 
                    v-model:current-page="currentPage" />

  <el-dialog v-loading="saveDialogLoading" v-model="saveDialogShow" :title="saveDialogTitle" :close-on-click-modal="false">
    <div>
        <el-form ref="formRef" inline :model="saveFormData" :rules="rules" style="display: flex; justify-content: space-around;">
            <el-form-item label="标题" prop="title">
                <el-input v-model="saveFormData.title"></el-input>
            </el-form-item>
            <el-form-item label="内容" prop="content">
                <el-input v-model="saveFormData.content"></el-input>
            </el-form-item>
            <el-form-item label="电话" prop="phone">
                <el-input v-model="saveFormData.phone"></el-input>
            </el-form-item>
        </el-form>
    </div>
    <template #footer>
        <div>
            <el-button type="primary" @click="submitForm()">确定</el-button>
            <el-button @click="saveDialogShow = false">取消</el-button>
        </div>
    </template>
  </el-dialog>

  <el-dialog v-model="importDialogShow" title="导入Excel" :close-on-click-modal="false" width="400">
    <div style="text-align: center;padding: 20px;">
        <el-upload
        :action="baseUrl + '/myRecords/import'"
        accept=".xlsx"
        :on-success="(response, file) => { if(response.code) { ElMessage({ message: '导入成功', type: 'success' }); getData(); importDialogShow = false; } else { ElMessage({ message: response.msg, type: 'error' }); } }"
        :on-error="(err, file) => { ElMessage({ message: '导入失败', type: 'error' }); }"
        :show-file-list="false">
            <el-button type="primary" size="large">点击上传</el-button>
        </el-upload>
    </div>
    <div style="text-align: center;">
        <a href="/docs/记录导入模板.xlsx" download>下载导入模板</a>
    </div>
  </el-dialog>
</template>

<script lang="ts" setup>
import { onMounted, ref, watch } from 'vue';
import { page, save, del } from '@/http/myRecords'
import { ElMessage, ElMessageBox, FormInstance } from 'element-plus'
import { validatePhone } from '@/util/regUtil';

const baseUrl = window.GLOBAL_CONFIG.BASE_URL
const tableData = ref([])
const totalData = ref(0)
const currentPage = ref(1)
const pageSize = ref(20)
const queryTitle = ref('')
const importDialogShow = ref(false)
const saveDialogShow= ref(false)
const saveDialogTitle = ref('')
const saveFormData = ref({})
const loading = ref(false)
const saveDialogLoading = ref(false)
const formRef = ref<FormInstance>()
const rules = ref({
    title: [{ required: true, message: '请输入标题' }],
    content: [{ required: true, message: '请输入内容' }],
    phone: [
        {
            message: '请输入有效的手机号',
            trigger: 'blur',
            validator: validateFormPhone
        }
    ]
})

function openSaveDialog(row) {
    if(!row) { // 新增
        saveDialogTitle.value = '新增'
        saveFormData.value = {
            createUser: 'test',
            updateUser: 'test'
        }
        saveDialogShow.value = true
    } else {
        saveDialogTitle.value = '修改'
        saveFormData.value = row
        saveDialogShow.value = true
    }
}
function submitForm() {
    formRef.value.validate(valid => {
        if(valid) {
            saveDialogLoading.value = true
            save(saveFormData.value).then(res => {
                saveDialogLoading.value = false
                if(res.data.code) {
                    ElMessage({
                        message: '保存成功',
                        type: 'success'
                    })
                    getData()
                }
                saveDialogShow.value = false
            })
        }
    })
}
function delData(row) {
    ElMessageBox.confirm('您确定要删除吗？', '', {
        type: 'warning'
    }).then(() => {
        del(row.id).then(res => {
            if(res.data.code) {
                ElMessage({
                    message: '删除成功！',
                    type: 'success'
                })
                getData()
            }
        })
    })
}
function getData() {
    loading.value = true
    page({
        pageNum: currentPage.value,
        pageSize: pageSize.value,
        title: queryTitle.value
    }).then(res => {
        if(res.data && res.data.code) {
            tableData.value = res.data.data.records
            totalData.value = res.data.data.total
            loading.value = false
        }
    })
}
function validateFormPhone(rule, value, callback) {
    if(!value || validatePhone(value)) {
        callback()
    } else {
        callback(new Error(rule.message))
    }
}
function getTableIndex(idx) {
    return (currentPage.value - 1) * pageSize.value + idx + 1;
}
function exportExcel() {
    window.open(window.GLOBAL_CONFIG.BASE_URL + "/myRecords/export", '_self')
}
function exportStatistics() {
    window.open(window.GLOBAL_CONFIG.BASE_URL + "/myRecords/exportStatistics", '_self')
}
function importExcel() {
    importDialogShow.value = true
}

watch(currentPage, (newVal, oldVal) => {
    getData()
})

onMounted(function() {
    getData()
})
</script>

<style scoped>
.mytable {
    width: 100%;
    height: calc(100vh - 200px);
    /* overflow-y: scroll; */
}
.el-pagination {
    justify-content: end;
    margin-top: 10px;
}
</style>